package com.joeshing.security.authentication;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.Assert;


public class SessionAuthenticationDetailsSource implements AuthenticationDetailsSource {
	
	private SessionUserSource sessionUserSource;
    private UsernamePasswordAuthenticationFilter usernamePasswordAuthenticationFilter;
	
	public void setUsernamePasswordAuthenticationFilter(
			UsernamePasswordAuthenticationFilter usernamePasswordAuthenticationFilter) {
		this.usernamePasswordAuthenticationFilter = usernamePasswordAuthenticationFilter;
	}
	
	public void setSessionUserSource(SessionUserSource sessionUserSource) {
		this.sessionUserSource = sessionUserSource;
	}
	
    public Object buildDetails(Object context) {
        Assert.isInstanceOf(HttpServletRequest.class, context);
        HttpServletRequest request = (HttpServletRequest)context;
        SessionAuthenticationDetails details = new SessionAuthenticationDetails();
		String uid = request.getParameter(usernamePasswordAuthenticationFilter.getUsernameParameter());
		String password = request.getParameter(usernamePasswordAuthenticationFilter.getPasswordParameter());
		details.setRemoteAddress(request.getRemoteAddr());
		if(uid!=null&&!uid.trim().equals("")){
			details.setUser(sessionUserSource.buildSessionUser(uid,password));
			details.setSessionTimeOut(sessionUserSource.getSessionTimeOut(uid));
		}
        return details;
    }

}
